package com.gin.no_gay_alliance.manager;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import androidx.annotation.NonNull;

import com.gin.common.utils.FileIoUtils;
import com.gin.nga.callback.JsonCallback;
import com.gin.nga.client.NgaClient;
import com.gin.nga.exception.NgaException;
import com.gin.nga.method.NukeApi;
import com.gin.nga.response.body.BaseMessageBody;
import com.gin.nga.response.body.nuke.NoticeBody;
import com.gin.no_gay_alliance.R;
import com.gin.no_gay_alliance.activity.NoticeActivity;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.callback.Callback;
import com.gin.no_gay_alliance.viewmodel.notice.NoticeDataModel;

import java.io.File;
import java.io.IOException;
import java.util.Locale;

import okhttp3.Call;

/**
 * 提醒消息管理器
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/8/18 17:13
 **/
public class NoticeManager {

    public static final String TAG = NoticeManager.class.getSimpleName();
    public static final String CHANNEL_ID = "notice";
    final Context context;
    private NoticeDataModel noticeData;

    public NoticeManager(Context context) {
        this.context = context;
        this.noticeData = load();
    }

    /**
     * 清空提醒消息
     */
    public void clear(Callback<String> callback) {
        NgaClient client = MyApplication.getClient();
        NukeApi.noticeClear(client).async(new JsonCallback<BaseMessageBody>() {
            @Override
            public void onSuccess(BaseMessageBody body) {
                if (getFile().delete()) {
                    noticeData.clear();
                    save(noticeData);
                    callback.onSuccess(body.getMessage());
                } else {
                    Log.d(TAG, "文件删除失败: " + getFile());
                }
            }
        });
    }

    /**
     * 请求提醒消息
     *
     * @param callback 回调
     */
    public void updateData(Callback<NoticeDataModel> callback) {
        NgaClient client = MyApplication.getClient();
        NukeApi.noticeList(client, noticeData.nextTime).async(new JsonCallback<NoticeBody>() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                super.onFailure(call, e);
                Log.w(TAG, "onFailure: " + e.getMessage());
            }

            @Override
            public void onSuccess(NoticeBody body) {
                // 合并数据并保存
                noticeData.merge(new NoticeDataModel(body.getData()));
                save(noticeData);
                // 发送推送
                sendNotification(noticeData);
                if (callback != null) {
                    callback.onSuccess(noticeData);
                }
            }

            @Override
            public void handleException(NgaException e) {
//                super.handleException(e);
//                Log.w(TAG, e.getMessage(), e);
                Log.d(TAG, "没有新消息");
                sendNotification(noticeData);
                if (callback != null) {
                    callback.handleException(e);
                }
            }
        });
    }

    /**
     * 保存数据到文件
     */
    public void save(NoticeDataModel noticeData) {
        this.noticeData = noticeData;
        Log.d(TAG, "保存提醒消息");
        try {
            FileIoUtils.writeObj(getFile(), noticeData);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 账号切换时调用
     */
    public void onAccountChanged() {
        this.noticeData = load();
        updateData(null);
    }

    /**
     * 从文件中读取提醒消息
     *
     * @return 文件中保存的提醒消息
     */
    @NonNull
    private NoticeDataModel load() {
        File noticeFile = getFile();
        if (!noticeFile.exists()) {
            return new NoticeDataModel();
        }
        try {
            NoticeDataModel data = FileIoUtils.readObj(noticeFile, NoticeDataModel.class);
            return data != null ? data : new NoticeDataModel();
        } catch (IOException e) {
            e.printStackTrace();
            return new NoticeDataModel();
        }
    }

    /**
     * 发送推送信息
     *
     * @param newData 新数据
     */
    private void sendNotification(NoticeDataModel newData) {
        long count = newData.countUnread();
        if (count == 0) {
            return;
        }
        NotificationUtils notificationUtils = MyApplication.app.managerFactory.getNotificationUtils();
        // 构建通知对象
        Notification notification;
        String message = String.format(Locale.CHINA, "你有 %d 条未读消息", count);
        Log.d(TAG, "sendNotification: " + message);

        //设置延时意图，点击打开提醒活动

        Intent intent = new Intent(MyApplication.app, NoticeActivity.class);
        int flags = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S ? PendingIntent.FLAG_IMMUTABLE : PendingIntent.FLAG_UPDATE_CURRENT;
        PendingIntent contentIntent = PendingIntent.getActivity(MyApplication.app, 0, intent, flags);
        NotificationChannel channel = notificationUtils.getChannel(CHANNEL_ID);
        notification = new Notification.Builder(MyApplication.app, channel.getId())
                .setSmallIcon(R.mipmap.ic_app_g)
                .setContentTitle(MyApplication.app.getString(R.string.app_name))
                .setContentText(message)
                .setAutoCancel(true)
                .setContentIntent(contentIntent)
                .build();

        int id = 0;
        notificationUtils.cancel(id);
        notificationUtils.publish(id, notification);
    }

    @NonNull
    private File getFile() {
        long userId = MyApplication.getClient().getUserId();
        File noticeDir = new File(context.getCacheDir(), CHANNEL_ID);
        return new File(noticeDir, userId + ".json");
    }

    public NoticeDataModel getNoticeData() {
        return noticeData != null ? noticeData : new NoticeDataModel();
    }
}
